package com.hwl.vod.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.google.common.collect.Lists;
import com.hwl.commonutils.exception.GuliException;
import com.hwl.commonutils.result.ResultCodeEnum;
import com.hwl.vod.service.VodService;
import com.hwl.vod.util.InitVodClient;
import com.hwl.vod.util.VodProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.List;

@Slf4j
@Service
public class VodServiceImpl implements VodService {

    @Resource
    private VodProperties vodProperties;

    @Override
    public String uploadVideo(InputStream inputStream, String originalFilename) {
        //上传之后显示的名称
        String title = originalFilename.substring(0, originalFilename.lastIndexOf("."));

        UploadStreamRequest request = new UploadStreamRequest(
                vodProperties.getKeyid(), vodProperties.getKeysecret(), title, originalFilename, inputStream);

        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadStreamResponse response = uploader.uploadStream(request);

        String videoId = response.getVideoId();
        //如果设置回调URL无效，不影响视频上传，可以返回videoId同时会返回错误码。
        //其他情况上传失败时，videoId为空，此时需要根据返回错误码分析具体错误原因
        if (StringUtils.isEmpty(videoId)) {
            log.error("视频上传失败：" + response.getCode() + "-" + response.getMessage());
            throw new GuliException(ResultCodeEnum.VIDEO_UPLOAD_ALIYUN_ERROR);
        }
        log.info("===========视频上传成功===========");
        return videoId;
    }

    @Override
    public void removeVideo(String videoId) {
        try {
            //初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(vodProperties.getKeyid(), vodProperties.getKeysecret());

            //创建删除视频request对象
            DeleteVideoRequest request = new DeleteVideoRequest();
            request.setVideoIds(videoId);
            //调用初始化对象的方法实现删除
            client.getAcsResponse(request);
            log.info("视频删除成功！");
        } catch (ClientException e) {
            log.error("视频删除失败！");
            throw new GuliException(ResultCodeEnum.VIDEO_DELETE_ALIYUN_ERROR);
        }
    }

    @Override
    public void removeListVideo(List<String> videoIdList) {
        try {
            DefaultAcsClient client = InitVodClient.initVodClient(vodProperties.getKeyid(), vodProperties.getKeysecret());
            DeleteVideoRequest request = new DeleteVideoRequest();

            //id集合不能超过20个
            if (videoIdList.size() <= 20) {
                String videoIds = String.join(",", videoIdList);
                //向request设置视频id，支持传入多个视频id，使用逗号分隔
                request.setVideoIds(videoIds);
                //调用初始化对象的方法实现删除
                client.getAcsResponse(request);
            } else {
                //这里有两种方法来分割list
                //List<List<String>> idLists = ListUtils.partition(videoIdList, 20);
                List<List<String>> idLists = Lists.partition(videoIdList, 20);

                for (List<String> ids : idLists) {
                    String videoIds = String.join(",", ids);
                    request.setVideoIds(videoIds);
                    client.getAcsResponse(request);
                }
            }

            log.info("批量删除{}个视频成功！", videoIdList.size());
        } catch (ClientException e) {
            log.error("批量删除{}个视频失败！", videoIdList.size());
            throw new GuliException(ResultCodeEnum.VIDEO_DELETE_ALIYUN_ERROR);
        }

    }

    @Override
    public String getPlayAuth(String videoSourceId) {
        try {
            DefaultAcsClient client = InitVodClient.initVodClient(
                    vodProperties.getKeyid(),
                    vodProperties.getKeysecret());

            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();//创建请求对象
            request.setVideoId(videoSourceId);//设置请求参数

            //发送请求得到响应
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            log.info("获取视频播放凭证成功！");
            return response.getPlayAuth();
        } catch (ClientException e) {
            log.error("获取视频播放凭证失败！");
            throw new GuliException(ResultCodeEnum.FETCH_PLAYAUTH_ERROR);
        }
    }
}
